import React, { useEffect, useRef, useState } from 'react';
import { Image, ScrollView, Text, View } from '@tarojs/components';
import { AtSearchBar, AtTabs, AtTabsPane } from 'taro-ui';
import store from '../../store';
import './index.less';
import TitleBar from '@/src/components/titleBar';
import Taro from '@tarojs/taro';
import classNames from 'classnames';
import { brandListFun } from '@/src/common/method/wikiFun';
import { observer } from 'mobx-react-lite';
import CommonBlank from '@/src/components/pageBlank';
import { netWorkErrorInfo } from '@/src/utils/constants';
const originList: any = {
  0: 1,
  1: 2,
  2: 3,
};
//百科页面
const EncyclopediaRedirect = () => {
  const [value, setValue] = useState('');
  const [current, setCurrent] = useState(0);
  const [loadingText, setLoadingText] = useState('加载中...');

  // 全部城市数据，按首字母分组
  const [cigaData, setCigaData] = useState<any>([]);
  // 右侧点击后要滚动到的 id
  const [scrollId, setScrollId] = useState<string>('');
  const [clickAble, setClickAble] = useState<boolean>(true); //是否可点击状态
  const [activeLetter, setActiveLetter] = useState('');
  const [indexList, setIndexList] = useState<any>([]);
  const scrollViewRef: any = useRef<HTMLDivElement>(null);
  // 添加滚动结束检测，避免滚动中频繁更新
  let scrollTimer: any = null;
  const isIos: any = store.commonStore.isIos;

  //品牌列表
  const getBrandList = (countryOfOrigin: number) => {
    brandListFun({
      countryOfOrigin: countryOfOrigin, //1 = 国产，2 = 古巴，3 =  非古巴
    }).then((res: any) => {
      setLoadingText('');
      const result: any = res.filter((item: any) => item.letterCount > 0);
      if (result && result.length > 0) {
        setActiveLetter(result[0].letterUp);
        const letterUpVal: any = [];
        result.forEach((item: any) => {
          letterUpVal.push(item.letterUp);
        });
        setIndexList(letterUpVal);
        setCigaData(result);
      } else {
        setCigaData([]);
        setIndexList([]);
      }
    });
  };
  useEffect(() => {
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    //品牌列表,默认古巴
    getBrandList(1);
  }, []);
  const tabList: any = [
    {
      title: '中国雪茄',
    },
    {
      title: '古巴雪茄',
    },
    {
      title: '非古雪茄',
    },
  ];

  const onChange = (value: any) => {
    setValue(value);
  };
  //切换tab，获取不同大类下的雪茄1 = 国产，2 = 古巴，3 =  非古巴
  const handleClick = (value: any) => {
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    getBrandList(originList[value]);
    setCurrent(value);
  };
  //跳转到品牌详情页
  const gotoDetail = (item: any) => {
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    Taro.navigateTo({
      url: `/subPagesWiki/brandDetail/index?brandId=${item.brandId}`,
    });
  };
  //跳转到百科搜索页面
  const gotoSearch = () => {
    //判断网络状态，如果没有网络则不可点击
    if (!store.commonStore.networkStatus) {
      Taro.showToast({ title: netWorkErrorInfo, icon: 'none' });
      return;
    }
    if (clickAble) {
      Taro.navigateTo({ url: '/subPagesWiki/wikiSearch/index' });
      setClickAble(false);
    }
    setTimeout(() => {
      setClickAble(true);
    }, 1000);
  };
  // 监听滚动位置
  const handleScroll = (e: any) => {
    clearTimeout(scrollTimer);
    scrollTimer = setTimeout(() => {
      // 查找当前应该高亮的字母
      let currentLetter = '';
      if (currentLetter && currentLetter !== activeLetter) {
        setActiveLetter(currentLetter);
      }
    }, 100);
  };

  const content = () => {
    return (
      <View className="wiki-container">
        <View className="body">
          {/* 左：雪茄列表 */}
          <ScrollView
            className="ciga-list"
            scrollY
            scrollIntoView={scrollId}
            scrollWithAnimation
            scrollTop={0}
            onScroll={(e: any) => handleScroll(e)}
            ref={scrollViewRef}
          >
            {cigaData &&
              cigaData.map((item: any, index: any) => {
                const list = item.letterUp;
                return (
                  <View
                    key={index}
                    id={`index-${item.brandId}`}
                    className="group"
                  >
                    <Text className="section-letter" id={`section-${list}`}>
                      {list}
                    </Text>

                    {item.brandList.map((itemNew: any) => {
                      return (
                        <View
                          className="home-wiki-item"
                          key={itemNew.brandId}
                          onClick={() => gotoDetail(itemNew)}
                        >
                          <View className="left">
                            <Image
                              src={itemNew.brandImg}
                              className="left-img"
                            />
                          </View>
                          <View className="right">
                            <View className="name clamp1">
                              {itemNew.brandNameEn}
                            </View>
                            <View className="brand">{itemNew.brandName}</View>
                            <View className="amount">
                              {itemNew.seriesCount || 0}个系列 |{' '}
                              {itemNew.productCount || 0}
                              支雪茄
                            </View>
                          </View>
                        </View>
                      );
                    })}
                  </View>
                );
              })}
            {cigaData && cigaData.length === 0 && loadingText === '' && (
              <CommonBlank visible={true} desc={'抱歉，暂无数据'} />
            )}
          </ScrollView>
        </View>
        {/* 右：字母索引 */}
        <View className="letter-index">
          {cigaData.map((letter) => (
            <Text
              key={letter}
              className={classNames(
                `index-letter letter-${activeLetter === letter.letterUp}`
              )}
              onClick={() => scrollToIndex(letter.letterUp)}
            >
              {letter.letterUp}
            </Text>
          ))}
        </View>
      </View>
    );
  };
  // 点击索引项，滚动到对应分组
  const scrollToIndex = (index: string) => {
    setActiveLetter(index);
    setScrollId(`section-${index}`);
  };
  return (
    <View
      className={`home-wiki-container home-wiki-container-${store.commonStore.safeAreaTop}`}
      style={{
        paddingTop: `${store.commonStore.safeAreaTop}rpx`,
        height: `calc(100vh - ${store.commonStore.safeAreaTop}rpx)`,
      }}
    >
      <TitleBar showLeftBack={false} title=""></TitleBar>
      <View className="home-wiki-search" onClick={() => gotoSearch()}>
        <AtSearchBar
          placeholder="搜索"
          className="custom-search-bar"
          value={value}
          showActionButton={true}
          onChange={() => onChange(value)}
          disabled
        />
      </View>
      <View
        className="home-wiki-content"
        style={{
          paddingTop: isIos
            ? '50px'
            : `calc(44px + ${store.commonStore.safeAreaBottom}rpx)`,
          height: `calc(100vh - (280rpx + ${store.commonStore.safeAreaTop}rpx ))`,
        }}
      >
        <AtTabs
          current={current}
          tabList={tabList}
          onClick={handleClick}
          className="common-tab"
        >
          <AtTabsPane current={current} index={0}>
            {/* 内容区：左右两列 */}
            {content()}
          </AtTabsPane>
          <AtTabsPane current={current} index={1}>
            {content()}
          </AtTabsPane>
          <AtTabsPane current={current} index={2}>
            {content()}
          </AtTabsPane>
        </AtTabs>
      </View>
    </View>
  );
};

export default observer(EncyclopediaRedirect);
